use clap::{arg, command, ArgAction, ArgMatches};
use std::path::Path;
use std::process::exit;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{self, Read, Write};
use std::time;
use std::fs;

fn main() {
    let matches = get_match();
    if let Some(listen) = matches.get_one::<String>("listen") {
        println!("listen: {listen}");
    } else {
        println!("listen: localhost");
    }
    if let Some(port) = matches.get_one::<String>("port") {
        println!("port: {port}");
    } else {
        println!("port: 12345");
    }

    let arg_dir = matches.get_many::<String>("DIR")
        .expect("no path");

    for dir in arg_dir {
        // println!("show dir {}",dir)
        let pth = Path::new(dir);
        if pth.is_dir() {
            println!(".");
        } else {
            exit(1);
        }
    }

    let listener = TcpListener::bind("localhost:12345").expect("TCP server initialize error!");

    let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();
    //创建一个容器，用来放线程的句柄

    for stream in listener.incoming() {
        let stream = stream.expect("failed");
        //转换一下stream流，出现问题，提示“失败”，没有问题，继续下面的操作
        let handle = thread::spawn(move || {
            handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error));
        });

        thread_vec.push(handle);
        //把handle加到容器里面
    }

    for handle in thread_vec {
        //此循环为了等待线程的结束
        handle.join().unwrap();
        //等待结束的具体实现
    }
}

/**
* 用于读取文件夹路径，返回文件名buf
*/
fn get_files_from_path(dir_path: &String) -> [u8; 512] {
    let paths = fs::read_dir(dir_path).unwrap();

    let mut files_buf = [0; 512];
    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }

    return files_buf;
}

fn handle_client(mut stream: TcpStream) -> io::Result<()> {
    //该函数用来处理client（就是这个流），流的格式或者说他的类型就是TcpStream
    let mut buf = [0; 512];
    //创建一个叫buf的数组，内容为0，长度为512
    loop {
        //该循环表示server端永久提供服务，因为默认服务器为永不关闭的
        let bytes_read = stream.read(&mut buf)?;
        //从流里面读内容，读到buf中
        if bytes_read == 0 {
            return Ok(());
            //如果读到的为空（即0），则说明已经结束了
        }
        stream.write(&buf[..bytes_read])?;
        //否则把它写回去
        thread::sleep(time::Duration::from_secs(1));
        //调用sleep函数实现服务的间隔，间隔1s
    }
}


fn get_match() -> ArgMatches {
    command!()
        .arg(
            arg!([DIR] "DIR to show")
        )
        .arg(arg!( -H --hidden "print the total line number only" )
            .action(ArgAction::SetTrue))
        .arg(arg!( -l --listen <"ADDRESS"> "specify source address to use [default is localhost]" ))
        .arg(arg!( -p --port <"PORT"> "specify listening port [default port is 12345]" ))
        .get_matches()
}
